package com.udaos.modules.card.controllers;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.adaptor.WhaleAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.base.Globals;
import com.udaos.common.base.Result;
import com.udaos.common.page.DataTableColumn;
import com.udaos.common.page.DataTableOrder;
import com.udaos.models.card.Ud_card_rack;
import com.udaos.models.sys.Sys_user;
import com.udaos.models.wx.Wx_config;
import com.udaos.modules.card.pojo.LandingPage;
import com.udaos.modules.card.services.UdCardRackService;
import com.udaos.modules.card.services.UdCardService;
import com.udaos.modules.card.services.UdWxCardService;
import com.udaos.modules.wx.services.WxConfigService;

import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMediaImgUploadResult;
import net.sf.json.JSONObject;

@IocBean
@At("/platform/cardrack")
public class UdCardRackController {

	@Inject
	private UdCardService cardService;
	@Inject
	private UdCardRackService cardRackService;
	@Inject
	private UdWxCardService cardInfoService;
	@Inject
	private WxConfigService wxConfigService;
	
	/**
	 * 首页
	 */
	@At("")
	@Ok("beetl:/platform/card/rack/index.html")
	@RequiresAuthentication
	public void index() {

	}
	
	/**
	 * 加载数据
	 * @param title
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full") 
	@RequiresAuthentication
	public Object data( @Param("title") String title,@Param("length") int length, @Param("start") int start,
			@Param("draw") int draw, @Param("::order") List<DataTableOrder> order,
			@Param("::columns") List<DataTableColumn> columns) {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			Cnd cnd = Cnd.NEW();
			//获取主体
			Sys_user user = (Sys_user) subject.getPrincipal();
			String company_id=user.getUnit().getCompany_id();
			cnd.and("company_id", "=", company_id);
			cnd.and("delFlag", "=", "0");
			if (!Strings.isBlank(title))
				cnd.and("title", "like", "%" + title + "%");
			return cardRackService.data(length, start, draw, order, columns, cnd, null);
		}else{
			return Result.error("system.error");
		}
	}
	
	/**
	 * 新增
	 * @return
	 */
	@At
	@Ok("beetl:/platform/card/rack/add.html")
	@RequiresAuthentication
	public Object add() {
		
		return cardService.queryOn();
	}
	
	@At("/addDo")
	@Ok("json")
	@RequiresAuthentication 
	@AdaptBy(type = WhaleAdaptor.class)
	public Object addDo(@Param("..") Ud_card_rack rack,HttpServletRequest request) {
		try{
			Subject subject = SecurityUtils.getSubject();
			if (subject != null) {
				Sys_user user = (Sys_user) subject.getPrincipal();
				//设置主体
				rack.setCompany_id(user.getUnit().getCompany_id());
				//设置创建时间
				rack.setCreateAt((int)(System.currentTimeMillis()/1000));
				//设置创建人
				rack.setCreateBy(user.getId());
				List<LandingPage> card_list=new ArrayList<LandingPage>();
				//设置图片
				// 获取微信相关信息
				Wx_config config=wxConfigService.fetch(Cnd.where("company_id", "=", user.getUnit().getCompany_id()));
				WxMpService wxMpService=getWxMpService(config.getId());
				File imgFile=new File(Globals.AppUploadPath+rack.getImg_url());//DownloadURLFileUtils.downloadFromUrl(imgUrl, UUID.randomUUID().toString(), rack.getImg_url().split("\\.")[1]) ;
				WxMediaImgUploadResult result=wxMpService.getMaterialService().mediaImgUpload(imgFile);
				String wx_img_url=result.getUrl();
				rack.setImg_url(wx_img_url);
				
				File card_img_urlFile=new File(Globals.AppUploadPath+rack.getCard_img_url());//DownloadURLFileUtils.downloadFromUrl(card_img_url, UUID.randomUUID().toString(), rack.getCard_img_url().split("\\.")[1]) ;
				WxMediaImgUploadResult result1=wxMpService.getMaterialService().mediaImgUpload(card_img_urlFile);
				String wx_card_img_url=result1.getUrl();
				rack.setCard_img_url(wx_card_img_url);
				
				String aa=rack.getCard_list();
				if(aa.startsWith("[")){
					aa=rack.getCard_list().substring(1, rack.getCard_list().length()-1);
				}
				String []card_list_=aa.split(",");
				if(null !=card_list_){
					for(String card_id:card_list_){
						LandingPage page=new LandingPage();
						page.setCard_id(card_id.trim());
						page.setThumb_url(rack.getCard_img_url());
						card_list.add(page);
					}
				}
				//获取微信ID
				Map<String,Object> map=cardInfoService.createWxlandingPage(config.getId(), card_list,rack.getImg_url(), rack.getTitle(), true, "SCENE_NEAR_BY");
				if(map.get("code").equals("1")){
					JSONObject json=(JSONObject) map.get("data");
					if(json.getInt("errcode")==0){
						rack.setRack_url(json.getString("url"));
						rack.setState(0);
						cardRackService.insert(rack);
					}
				}else{
					return Result.error("system.error");
				}
				return Result.success("system.success");
			}
			return Result.error("system.error");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
	
	
	/**
	 * 获取微信公众号服务
	 * 
	 * @param wxid
	 * @return
	 */
	public WxMpService getWxMpService(String wxid) {
		WxMpConfigStorage config = getWxConfig(wxConfigService.fetch(wxid));
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(config);
		return wxMpService;
	}
	/**
	 * 获取公众号配置
	 * 
	 * @param appInfo
	 * @return
	 */
	public WxMpConfigStorage getWxConfig(Wx_config appInfo) {
		if (null == appInfo)
			return null;
		WxMpConfigStorage config = new WxMpInMemoryConfigStorage();
		((WxMpInMemoryConfigStorage) config).setAppId(appInfo.getAppid()); // 设置微信公众号的appid
		((WxMpInMemoryConfigStorage) config).setSecret(appInfo.getAppsecret()); // 设置微信公众号的app
		((WxMpInMemoryConfigStorage) config).setToken(appInfo.getToken()); // 设置微信公众号的token
		((WxMpInMemoryConfigStorage) config).setAesKey(appInfo.getEncodingAESKey()); // 设置微信公众号的EncodingAESKey

		return config;
	}
}
